// src/views/account/Admin.tsx
import menus, { MyMenuItem } from '@/router/menus';
import { Button, Drawer, Space, Table, Tree, Input, Select, Popconfirm, Modal, notification } from 'antd';
import React, { useState, FC, useEffect } from 'react';
import type { DataNode } from 'antd/es/tree';
import type { ColumnsType } from 'antd/es/table';

import { addAdmin, deleteAdmin, getAdminList, updateAdmin } from '@/api/admin'
import { useAppSeletor } from '@/store/hooks';
interface AccountAdminProps {}

interface DataType {
  adminid: string;
  adminname: string;
  role: number;
  checkedKeys: string[];
}

// 处理数据
function getTreeData (menus: MyMenuItem[]) {
  const arr: DataNode[]= []
  menus.forEach(item => {
    let obj: DataNode;
    if (item.children) {
      const childArr = getTreeData(item.children)
      obj = {
        key: item.key!,
        title: item.label,
        children: childArr
      }
    } else {
      obj = {
        key: item.key!,
        title: item.label
      }
    }
    arr.push(obj)
  })
  return arr
}

const AccountAdmin: FC<AccountAdminProps> = () => {
  const adminnameStr = useAppSeletor(state => state.admin.adminname)
  // 分页器配置
  const [current, setCurrent] = useState(1)
  const [pageSize , setPageSize] = useState(10)

  const [isModalOpen, setIsModalOpen] = useState(false);

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      render: (text: any, record: DataType, index: number) => {
        return <span>{ (current - 1) * pageSize + index + 1}</span>
      }
    },
    {
      title: '管理员账户',
      dataIndex: 'adminname'
    },
    {
      title: '角色',
      dataIndex: 'role',
      render: (text: number) => {
        return (<span>{ text === 2 ? '超级管理员' : '管理员'}</span>)
      }
    },
    {
      title: '操作',
      render: (text: any, record: DataType) => {
        return (
          <Space>
            <Button type="dashed" onClick={() => {
              setIsModalOpen(true)
              setAdminname(record.adminname)
              setRole(record.role)
              setCheckedKeys(record.checkedKeys)
            }}>编辑</Button>
            <Popconfirm
              title="删除"
              description="确定删除吗?"
              onConfirm={ () => {
                deleteAdmin({ adminid: record.adminid }).then(() => {
                  getAdminListDataFn()
                })
              }}
              onCancel={() => {}}
              okText="确定"
              cancelText="取消"
            >
              <Button danger>删除</Button>
            </Popconfirm>
          </Space>
        )
      }
    }
  ]
  const [adminList, setAdminList] = useState<DataType[]>([])
  const [open, setOpen] = useState(false); // 打开添加管理员的抽屉
  const showDrawer = () => { // 展示抽屉
    setOpen(true);
  };

  const onClose = () => { // 隐藏抽屉
    setOpen(false);
  };

  // 树形菜单的数据
  const [treeData, setTreeData] = useState<DataNode[]>([])
  // console.log(treeData)
  useEffect(() => { // 设置树形菜单的数据
    setTreeData(getTreeData(menus))
    getAdminListDataFn()
  }, [])
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>(['/']); // 默认情况下 系统首页是每个用户都需要访问的

  const onCheck = (checkedKeys: any) => { // 选择管理员的权限
    console.log('onCheck', checkedKeys);
    setCheckedKeys(checkedKeys);
  };

  // 设计表单的数据
  const [adminname, setAdminname] = useState('')
  const [password, setPassword] = useState('')
  const [role, setRole] = useState(1)
  
  const changeAdminnameValue = ({ target }: { target: HTMLInputElement}) => {
    // console.log(event.target.value)
    setAdminname(target.value)
  }
  const changePasswordValue = ({ target }: { target: HTMLInputElement}) => {
    setPassword(target.value)
  }
  const changeRoleValue = (value: number) => {
    setRole(value)
  }

  const addAdminFn = () => {
    const data = {
      adminname, password, role, checkedKeys
    }
    // console.log(data)

    addAdmin(data).then(() => {
      // console.log('添加成功')
      // 添加成功，清空表单的数据，抽屉消失，请求列表的最新数据
      setAdminname('')
      setPassword('')
      setRole(1)
      setCheckedKeys(['/'])
      onClose()
      getAdminListDataFn()
    })
  }

  const getAdminListDataFn = () => {
    // console.log('请求最新的列表数据')
    getAdminList().then(res => {
      // console.log('list', res.data.data)
      setAdminList(res.data.data)
    })
  }

  const [height] = useState(document.body.offsetHeight) // 计算body的高度
  // console.log('height', height)

 
  const updateAdminFn = () => {
    const data = {
      adminname, role, checkedKeys
    }
    updateAdmin(data).then(() => {
      getAdminListDataFn()
      setIsModalOpen(false)
      setAdminname('')
      setPassword('')
      setRole(1)
      setCheckedKeys(['/'])
    })
  }
  const [checkArr, setCheckArr] = useState<DataType[]>([])
  const [selectionType, setSelectionType] = useState<'checkbox'>('checkbox');
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setCheckArr(selectedRows)
    }
  }


  const [api, contextHolder] = notification.useNotification();
  return (
    <Space direction='vertical' style={{ width: '100%'}}>
      <Space>
        {contextHolder}
        <Button type="primary" onClick={() => showDrawer()}>添加管理员</Button>
        { checkArr.length > 0 ? <Button type="primary" onClick={() => {
          if (adminnameStr === 'admin') {
            const deleteArr: any[] = []
            checkArr.forEach(item => {
              deleteArr.push(deleteAdmin({adminid: item.adminid}))
            })
            Promise.all(deleteArr).then(() => {
              getAdminListDataFn()
            })
          } else {
            api.open({
              message: '提示信息',
              description: '没有权限，请向相关管理提交申请',
              duration: 2
            });
          }
        }}>批量删除</Button> : null }
      </Space>
      {
        adminnameStr === 'admin' ?
        <Table 
        rowSelection={{
          hideSelectAll: true,
          type: selectionType,
          ...rowSelection,
        }}
        columns={columns} 
        dataSource={adminList} 
        rowKey="adminid"
        scroll={{ y: height - 330 }}
        pagination={{
          current, 
          pageSize,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 20, 50],
          showQuickJumper: true,
          showTotal: (total) => `共有 ${total} 条数据`,
          onChange: (page, pageSize) => {
            setCurrent(page)
            setPageSize(pageSize)
          }
        }}
      ></Table> :
      <Table 
        columns={columns} 
        dataSource={adminList} 
        rowKey="adminid"
        scroll={{ y: height - 330 }}
        pagination={{
          current, 
          pageSize,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 20, 50],
          showQuickJumper: true,
          showTotal: (total) => `共有 ${total} 条数据`,
          onChange: (page, pageSize) => {
            setCurrent(page)
            setPageSize(pageSize)
          }
        }}
      ></Table>
      }
      <Drawer title="Basic Drawer" placement="right" onClose={onClose} open={open}>
        <Space direction='vertical' style={{ width: '100%'}}>
          <Input placeholder='管理员账户' value={adminname}  onChange={ changeAdminnameValue }/>
          <Input placeholder='管理员密码' value={password}  onChange={ changePasswordValue }/>
          <Select style={{ width: '100%' }} value ={ role } onChange={ changeRoleValue }>
            <Select.Option value={1}>管理员</Select.Option>
            <Select.Option value={2}>超级管理员</Select.Option>
          </Select>
          <Tree
            checkable
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            treeData={treeData}
          />

          <Button type="primary" onClick={() => addAdminFn()}>添加</Button>
        </Space>
      </Drawer>
      <Modal title="修改管理员的权限" open={isModalOpen} footer={null} onCancel={() => {
        setIsModalOpen(false)
        setAdminname('')
        setPassword('')
        setRole(1)
        setCheckedKeys(['/'])
      }}>
        <Space direction='vertical' style={{ width: '100%'}}>
          <Input placeholder='管理员账户' value={adminname} disabled/>
          <Select style={{ width: '100%' }} value ={ role } onChange={ changeRoleValue }>
            <Select.Option value={1}>管理员</Select.Option>
            <Select.Option value={2}>超级管理员</Select.Option>
          </Select>
          <Tree
            checkable
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            treeData={treeData}
          />

          <Button type="primary" onClick={() => updateAdminFn()}>更新</Button>
        </Space>
      </Modal>
    </Space>
  );
}

export default AccountAdmin;